package com.ksyun.ks3.services.handler;

import android.annotation.SuppressLint;
import android.util.Log;

import com.ksyun.ks3.exception.Ks3ClientException;
import com.ksyun.ks3.exception.Ks3ServiceException;
import com.ksyun.ks3.model.result.PutObjectResult;
import com.ksyun.ks3.model.transfer.RequestProgressListener;
import com.ksyun.ks3.services.request.Ks3HttpRequest;
import com.ksyun.ks3.services.request.PutObjectRequest;
import com.ksyun.ks3.util.ResponseUtils;

import okhttp3.Headers;


public abstract class PutObjectResponseHandler extends Ks3HttpResponseHandler implements RequestProgressListener {

    public abstract void onTaskFailure(PutObjectRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException);

    public abstract void onTaskSuccess(PutObjectRequest request, PutObjectResult result);

    public abstract void onTaskCancel();

    public abstract void onTaskProgress(double progress);

    @Override
    public final void onSuccess(Ks3HttpRequest request, int statusCode, Headers responseHeaders, byte[] response) {
        PutObjectResult result = new PutObjectResult();
        result.setStatusCode(statusCode);
        result.setHeaders(ResponseUtils.parseResponseHeaders(responseHeaders));
        this.onTaskSuccess((PutObjectRequest) request, result);
    }

    @Override
    public final void onFailure(Ks3HttpRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
        this.onTaskFailure((PutObjectRequest) request, clientException, serviceException);
    }

    @Override
    public final void onCancel() {
        onTaskCancel();
    }

    @Override
    public final void onProgress(long bytesWritten, long totalSize) {
        double progress =
                Double.valueOf(totalSize > 0 ? bytesWritten * 1.0D / totalSize * 100.0D : -1.0D);
        onTaskProgress(progress);
    }


    @SuppressLint("LongLogTag")
    @Override
    protected void finalize() throws Throwable {
        Log.d("PutObjectResponseHandler", "PutObjectResponseHandler finalize:" + this);
        super.finalize();
    }


}
